import * as vscode from 'vscode';
import OpenAI from 'openai';

// Initialize OpenAI client - in a real implementation, this would be configured by the user
let openai: OpenAI | null = null;

export async function initializeOpenAIClient(apiKey: string) {
    if (apiKey) {
        openai = new OpenAI({ apiKey });
    }
}

export async function analyzeCode(code: string): Promise<string> {
    // Validate code input
    if (!code || code.trim().length === 0) {
        return "no code to analyze";
    }

    // Get configuration settings
    const config = vscode.workspace.getConfiguration('codeReader');
    const apiKey = config.get<string>('apiKey', '');
    const model = config.get<string>('model', 'gpt-3.5-turbo');

    // Initialize the client if we have an API key and it hasn't been initialized yet
    if (apiKey && !openai) {
        await initializeOpenAIClient(apiKey);
    }

    // For demo purposes, we'll provide a mock response if API key is not set
    // In a production environment, you would want to handle this differently
    if (!openai) {
        // Simple heuristic analysis as fallback
        const lines = code.split('\n');
        if (lines.length === 1) {
            if (code.toLowerCase().includes('function') || code.toLowerCase().includes('def ')) {
                return `a function definition`;
            } else if (code.toLowerCase().includes('class')) {
                return `a class definition`;
            } else if (code.toLowerCase().includes('return')) {
                return `a return statement`;
            } else if (code.toLowerCase().includes('if') || code.toLowerCase().includes('else') || code.toLowerCase().includes('elif')) {
                return `a conditional statement`;
            } else if (code.toLowerCase().includes('for') || code.toLowerCase().includes('while')) {
                return `a loop`;
            } else {
                return `the functionality of the selected code`;
            }
        } else {
            return `a code block with ${lines.length} lines`;
        }
    }

    try {
        const response = await openai.chat.completions.create({
            model: model,
            messages: [
                {
                    role: "system",
                    content: "You are a code analysis assistant. Describe the functionality of the provided code in a clear and concise way. Return only your analysis without additional text or explanations."
                },
                {
                    role: "user",
                    content: `Analyze this code and describe its functionality:\n\n${code}`
                }
            ],
            max_tokens: 150
        });

        const result = response.choices[0].message.content;
        return result ? result.trim() : "the functionality of the selected code";
    } catch (error) {
        console.error('Error calling OpenAI API:', error);
        // Return a fallback analysis if API call fails
        const lines = code.split('\n');
        if (lines.length === 1) {
            if (code.toLowerCase().includes('function') || code.toLowerCase().includes('def ')) {
                return `a function definition`;
            } else if (code.toLowerCase().includes('class')) {
                return `a class definition`;
            } else if (code.toLowerCase().includes('return')) {
                return `a return statement`;
            } else if (code.toLowerCase().includes('if') || code.toLowerCase().includes('else') || code.toLowerCase().includes('elif')) {
                return `a conditional statement`;
            } else if (code.toLowerCase().includes('for') || code.toLowerCase().includes('while')) {
                return `a loop`;
            } else {
                return `the functionality of the selected code`;
            }
        } else {
            return `a code block with ${lines.length} lines`;
        }
    }
}